package com.douqu.game.core.entity.ext.data.card;

import com.bean.core.buffer.ByteBuffer;
import com.bean.core.util.Utils;
import com.douqu.game.core.config.InitDataConfig;
import com.douqu.game.core.config.PlayerLvConfig;
import com.douqu.game.core.config.StableDataConfig;
import com.douqu.game.core.config.VipConfig;
import com.douqu.game.core.config.card.*;
import com.douqu.game.core.config.common.CommonData;
import com.douqu.game.core.config.common.GoodsData;
import com.douqu.game.core.config.goods.*;
import com.douqu.game.core.controller.PlayerController;
import com.douqu.game.core.e.*;
import com.douqu.game.core.entity.Player;
import com.douqu.game.core.entity.common.TwoTuple;
import com.douqu.game.core.entity.db.AccessoryDB;
import com.douqu.game.core.entity.db.CardDB;
import com.douqu.game.core.entity.db.EquipDB;
import com.douqu.game.core.entity.db.PropDB;
import com.douqu.game.core.entity.ext.BagInfo;
import com.douqu.game.core.entity.ext.TaskInfo;
import com.douqu.game.core.entity.ext.data.BaseData;
import com.douqu.game.core.entity.ext.data.boon.FlashSaleRecord;
import com.douqu.game.core.factory.*;
import com.douqu.game.core.protobuf.SGBagProto;
import com.douqu.game.core.protobuf.SGBagProto.EquipIntensifyGroup;
import com.douqu.game.core.protobuf.SGCommonProto;
import com.douqu.game.core.protobuf.SGMainProto;
import com.douqu.game.core.protobuf.SGPlayerProto;
import com.douqu.game.core.util.CoreUtils;
import com.douqu.game.core.util.LogUtils;
import com.douqu.game.core.util.NoticeUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author: Gavin. Description: Date: 2017/11/22 0022 上午 10:48 Huan Yu Copyright
 * (c) 2017 All Rights Reserved.
 */
public class CardData extends BaseData {

    protected Player player;
    /**
     * 玩家所有的卡片map
     */
    private Map<Integer, CardDB> cardMap;
    /**
     * 玩家未上阵的卡片list
     */
    private List<CardDB> sleepCardList;
    /**
     * 玩家上阵卡组
     */
    private List<CardDB> battleCardList;
    private BagInfo bagInfo;

    /**
     * 军团连锁 <连锁id， 连锁下标>
     **/
    private Map<Integer, Integer> legionChinaMap;

    public CardData(Player player, BagInfo bagInfo) {
        this.player = player;
        this.bagInfo = bagInfo;
        sleepCardList = new CopyOnWriteArrayList<>();
        battleCardList = new CopyOnWriteArrayList<>();
        cardMap = new ConcurrentHashMap<>();
        legionChinaMap = new HashMap<>();
    }

    @Override
    public void init() {
        CardDB bagCard = null;

        DataFactory dataFactory = DataFactory.getInstance();

        List<InitDataConfig> initDataConfigList = InitDataConfig.getConfigByType(E_InitDataType.CARDS, false);
        if (initDataConfigList == null || initDataConfigList.size() == 0) {
            LogUtils.error("InitDataConfig error ->" + "no have type " + E_InitDataType.CARDS.getMsg());
            return;
        }

        InitDataConfig initDataConfig = initDataConfigList.get(0);
        for (Integer id : initDataConfig.initCards) {
            bagCard = new CardDB(id, player);
            bagCard.battle = true;

            addBattleCard(bagCard);
        }

        PlayerLvConfig playerLvConfig = dataFactory.getGameObject(DataFactory.PLAYER_LV_KEY, player.getLv());
        if (playerLvConfig != null) {
            int maxCardCount = playerLvConfig.battleSoldierCount;
            int minCardCount = playerLvConfig.minBattleSoldierCount;
            if (battleCardList.size() > maxCardCount || battleCardList.size() < minCardCount)
                LogUtils.error("PlayerLv 配置出错 -> maxCardCount:" + maxCardCount + ",minCardCount:" + minCardCount
                        + ",currentCardCount:" + battleCardList.size() + " playerLv->" + player.getLv() + ",uid ->" + player.getUid());
        }
    }

    @Override
    public void checkInit() {
        if (cardMap.size() == 0)
            init();
    }

    @Override
    public void reset() {

    }

    @Override
    public void checkReset() {

    }

    @Override
    public void writeTo(ByteBuffer buffer) {
        buffer.writeShort(sleepCardList.size());
        for (CardDB cardDB : sleepCardList) {
            cardDB.writeTo(buffer);
        }

        buffer.writeShort(battleCardList.size());
        for (CardDB cardDB : battleCardList) {
            cardDB.writeTo(buffer);
        }
    }

    @Override
    public void loadFrom(ByteBuffer buffer) {
        // 读取卡牌数据

        int size = buffer.readShort();
        int i = 0;
        CardDB cardDB = null;
        for (i = 0; i < size; i++) {
            cardDB = new CardDB(player);
            cardDB.loadFrom(buffer);
            if (cardDB.getConfig() == null) {
                try {
                    throw new Exception("BagInfo load error -> Sleep Card is null:" + cardDB.id);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                sleepCardList.add(cardDB);
                cardMap.put(cardDB.id, cardDB);
            }
        }

        size = buffer.readShort();
        for (i = 0; i < size; i++) {
            cardDB = new CardDB(player);
            cardDB.loadFrom(buffer);
            if (cardDB.getConfig() == null) {
                try {
                    throw new Exception("BagInfo load error -> Battle Card is null:" + cardDB.id);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                cardDB.battle = true;
                battleCardList.add(cardDB);
                cardMap.put(cardDB.id, cardDB);
            }
        }

        int max = getMaxCardSlotCount();
        if (size > max) {
            List<CardDB> tempList = battleCardList.subList(max, size);
            for (CardDB cardDB1 : tempList) {
                changeCardBattleStatus(cardDB1, false);
            }
        }
    }

    public CardDB getMaxFCSleepCard() {
        if (sleepCardList.size() == 0)
            return null;

        return Collections.max(sleepCardList, new Comparator<CardDB>() {
            @Override
            public int compare(CardDB o1, CardDB o2) {
                return new Integer(o1.fc).compareTo(o2.fc);
            }
        });
    }

    /**
     * 获取 某 品质卡牌的数量
     *
     * @param quality
     * @return
     */
    public int getCountByQuality(int quality) {
        int count = 0;
        for (Map.Entry<Integer, CardDB> entry : cardMap.entrySet()) {
            if (entry.getValue().getQuality() == quality) {
                count++;
            }
        }
        return count;
    }

    /**
     * 获取 某 品质卡牌最高的星数
     *
     * @param quality
     * @return
     */
    public int getStarByQuality(int quality) {
        int highest = 1;
        CardDB cardDb;
        for (Map.Entry<Integer, CardDB> entry : cardMap.entrySet()) {
            cardDb = entry.getValue();
            if (cardDb.getQuality() == quality) {
                if (cardDb.star > highest)
                    highest = cardDb.star;
            }
        }
        return highest;
    }

    /***
     * 上阵卡组列表
     */
    public void myCardTeam(PlayerController playerController) {
        SGBagProto.S2C_MyCardTeam.Builder b = SGBagProto.S2C_MyCardTeam.newBuilder();
        // 取出上证卡组id
        SGCommonProto.CardGroup.Builder c = SGCommonProto.CardGroup.newBuilder();
        c.setGroupId(SGCommonProto.E_CARDGROUP_TYPE.CARDGROUP_TYPE_BATTLE_VALUE);
        for (CardDB cardDB : battleCardList) {
            SGCommonProto.Card.Builder v = SGCommonProto.Card.newBuilder();
            v.setLv(cardDB.getLv());
            // 已拥有的碎片v
            v.setStar(cardDB.star);
            v.setId(cardDB.id);
            v.setCurExp(cardDB.getExp());
            v.setFc(cardDB.fc);
            c.addCards(v);
        }
        b.addCardGroups(c);
        // 返回给客户端
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Bag_MyCardTeam_VALUE, b.build().toByteArray());

    }

    /***
     * 设置上阵卡组
     *
     * @param playerController
     * @param cardTeamId
     */
    /*
     * public void setBattleCardTeam(PlayerController playerController,int
     * cardTeamId) {
     *
     * if(cardTeamMap.get(cardTeamId) == null) { //参数错误
     * playerController.sendWarn(WordFactory.PARAM_ERROR)); return; }
     *
     * battleCardIndex = cardTeamId; SGBagProto.S2S_SetBattleCardTeam.Builder b =
     * SGBagProto.S2S_SetBattleCardTeam.newBuilder(); b.setCardTeamId(cardTeamId);
     * playerController.sendMsg(SGMainProto.E_MSG_ID.
     * MsgID_Bag_SetBattleCardTeam_VALUE, b.build().toByteArray()); }
     */

    /***
     * 卡片替换使用
     *
     * @param playerController
     * @param activeCardId
     *            要上阵的卡牌
     * @param passiveCardId
     *            要替换下来的卡牌
     */
    public void cardReplace(PlayerController playerController, int cardTeamId, int activeCardId, int passiveCardId) {
        CardDB toBattleCard = cardMap.get(activeCardId);
        if (notingError(playerController, toBattleCard)) {
            return;
        }
        if (toBattleCard.battle) {
            // 已经是上阵的了
            playerController.sendWarn(WordFactory.CARD_IN_CARD_BATTLE_GROUP);
            return;
        }

        // 新增一个卡牌到上阵列表中
        if (passiveCardId == 0) {
            PlayerLvConfig playerLvConfig = DataFactory.getInstance().getGameObject(DataFactory.PLAYER_LV_KEY,
                    playerController.getPlayer().getLv());
            int battleCount = playerLvConfig.battleSoldierCount;

            VipConfig vipConfig = null;
            int vipBattleCount = 0;
            vipConfig = DataFactory.getInstance().getGameObject(DataFactory.VIP_KEY,
                    playerController.getPlayer().getVipLevel());
            if (vipConfig == null) {
                playerController.sendWarn(WordFactory.PARAM_ERROR);
                return;
            } else {
                vipBattleCount = vipConfig.additionalCard;
                battleCount += vipBattleCount;
            }

            int battleCardNum = battleCardList.size();
            if (battleCardNum >= battleCount) {
                // 上阵卡组中的卡牌不能大于当前能携带进战斗的兵种数量
                playerController.sendWarn(WordFactory.CANNOT_BE_GREATER_THAN_THE_NUMBER_OF_CARRY, battleCount);
                return;
            }

            changeCardBattleStatus(toBattleCard, true);
        } else {
            CardDB sleepCard = cardMap.get(passiveCardId);
            // 此卡牌不在未上阵卡组
            if (sleepCard == null) {
                playerController.sendWarn(WordFactory.CARD_NOTHING_ERROR, sleepCard.id);
                return;
            }
            if (!sleepCard.battle) {
                // 卡牌本来就不再上阵中
                playerController.sendWarn(WordFactory.CARD_NOT_IN_CARD_BATTLE_GROUP);
                return;
            }

            changeCardBattleStatus(toBattleCard, true);

            changeCardBattleStatus(sleepCard, false);
        }
        SGBagProto.S2C_CardReplace.Builder b = SGBagProto.S2C_CardReplace.newBuilder();
        b.setCardGroupId(cardTeamId);
        b.setActiveCardId(activeCardId);
        b.setPassiveCardId(passiveCardId);
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Bag_SetCardReplace_VALUE, b.build().toByteArray());
        calculateLegionChinaResult(E_LegionChinaType.ALL, playerController);
    }

    /**
     * 快捷上阵
     *
     * @param playerController
     * @param upList
     * @param downList
     */
    public void cardReplaceByOneKey(PlayerController playerController, List<Integer> upList, List<Integer> downList) {
        if (upList.isEmpty() || (!downList.isEmpty() && upList.size() != downList.size())) {
            playerController.sendWarn(WordFactory.PARAM_ERROR);
            return;
        }

        for (int cardId : upList) {
            // 卡牌是否存在
            CardDB toBattleCard = cardMap.get(cardId);
            if (notingError(playerController, toBattleCard)) {
                return;
            }
            if (toBattleCard.battle) {
                // 已经是上阵的了
                playerController.sendWarn(WordFactory.CARD_IN_CARD_BATTLE_GROUP);
                return;
            }
        }

        for (int cardId : downList) {
            // 卡牌是否存在
            CardDB toBattleCard = cardMap.get(cardId);
            if (notingError(playerController, toBattleCard)) {
                return;
            }
            if (!toBattleCard.battle) {
                // 并未在阵上
                playerController.sendWarn(WordFactory.CARD_NOT_IN_CARD_BATTLE_GROUP);
                return;
            }
        }

        if (downList.isEmpty()) {
            PlayerLvConfig playerLvConfig = DataFactory.getInstance().getGameObject(DataFactory.PLAYER_LV_KEY,
                    playerController.getPlayer().getLv());
            int battleCount = playerLvConfig.battleSoldierCount; // 玩家等级可以放置战斗的卡牌数量
            VipConfig vipConfig = DataFactory.getInstance().getGameObject(DataFactory.VIP_KEY,
                    playerController.getPlayer().getVipLevel());
            if (vipConfig == null) {
                playerController.sendWarn(WordFactory.PARAM_ERROR);
                return;
            } else {
                battleCount += vipConfig.additionalCard; // VIP加成的上阵卡牌数量
            }

            if (battleCardList.size() + upList.size() > battleCount) {
                // 上阵卡组中的卡牌不能大于当前能携带进战斗的兵种数量
                playerController.sendWarn(WordFactory.CANNOT_BE_GREATER_THAN_THE_NUMBER_OF_CARRY, battleCount);
                return;
            }
        }

        // 更改战斗状态
        for (int cardId : upList) {
            changeCardBattleStatus(cardMap.get(cardId), true);
        }
        for (int cardId : downList) {
            changeCardBattleStatus(cardMap.get(cardId), false);
        }

        SGBagProto.C2S_FastToBattle.Builder b = SGBagProto.C2S_FastToBattle.newBuilder();
        b.addAllUp(upList);
        b.addAllDown(downList);
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Player_FastToBattle_VALUE, b.build().toByteArray());
        calculateLegionChinaResult(E_LegionChinaType.ALL, playerController);
    }

    /**
     * 获取最大卡槽数量
     *
     * @return
     */
    public int getMaxCardSlotCount() {
        PlayerLvConfig playerLvConfig = DataFactory.getInstance().getGameObject(DataFactory.PLAYER_LV_KEY,
                player.getLv());
        VipConfig vipConfig = DataFactory.getInstance().getGameObject(DataFactory.VIP_KEY, player.getVipLevel());
        return playerLvConfig.battleSoldierCount + vipConfig.additionalCard;
    }

    /**
     * 设置卡牌上下阵情况
     *
     * @param cardDB
     * @param toBattle
     */
    public void changeCardBattleStatus(CardDB cardDB, boolean toBattle) {
        if (toBattle) {
            // 设置上阵
            cardDB.battle = true;
            battleCardList.add(cardDB);
            sleepCardList.remove(cardDB);
        } else {
            // 设置待上阵
            cardDB.battle = false;
            battleCardList.remove(cardDB);
            sleepCardList.add(cardDB);
        }
        calculateLegionChinaResult(E_LegionChinaType.ALL);
    }

    /***
     * 在战斗卡组中下阵
     *
     * @param playerController
     * @param cardTeamId
     * @param activeCardId
     */
    public void quitBattle(PlayerController playerController, int cardTeamId, int activeCardId) {
        CardDB toBattleCard = cardMap.get(activeCardId);
        if (notingError(playerController, toBattleCard)) {
            return;
        }
        if (!toBattleCard.battle) {
            // 不在上阵卡组中
            playerController.sendWarn(WordFactory.CARD_NOT_IN_CARD_BATTLE_GROUP);
            return;
        }
        // PlayerLvConfig playerLvConfig =
        // DataFactory.getInstance().getGameObject(DataFactory.PLAYER_LV_KEY,
        // playerController.getPlayer().getLv());
        // int battleCardNum = battleCardList.size();
        // int minBattleCount = playerLvConfig.minBattleSoldierCount;
        // if (battleCardNum <= minBattleCount) {
        // //上阵卡组中的卡牌不能小于当前能携带进战斗的兵种数量
        // playerController.sendWarn(WordFactory.CANNOT_BE_LESS_THAN_THE_NUMBER_OF_CARRY,minBattleCount);
        // return;
        // }

        // 设置待上阵
        toBattleCard.battle = false;
        battleCardList.remove(toBattleCard);
        sleepCardList.add(toBattleCard);

        SGBagProto.S2C_QuitBattleGroup.Builder b = SGBagProto.S2C_QuitBattleGroup.newBuilder();
        b.setCardGroupId(cardTeamId);
        b.setActiveCardId(activeCardId);
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Bag_QuitBattleGroup_VALUE, b.build().toByteArray());

        calculateLegionChinaResult(E_LegionChinaType.ALL, playerController);
    }

    /**
     * 卡牌id
     *
     * @param playerController
     * @param cardId
     */
    public void cardDetail(PlayerController playerController, int cardId) {
        CardDB cardDB = cardMap.get(cardId);
        if (notingError(playerController, cardDB)) {
            return;
        }
        SGBagProto.S2C_CardDetail.Builder b = SGBagProto.S2C_CardDetail.newBuilder();
        SGCommonProto.Card.Builder cardInfo = SGCommonProto.Card.newBuilder();
        cardInfo.setId(cardId);
        cardInfo.setCurExp(cardDB.getExp());
        cardInfo.setFc(playerController.getPlayer().fc);
        cardInfo.setLv(cardDB.getLv());
        cardInfo.setStar(cardDB.star);

        SGCommonProto.Accessory.Builder accessory = null;
        SGCommonProto.Equip.Builder equip = null;
        // 饰品
        for (Map.Entry<Integer, AccessoryDB> entry : cardDB.getAccessoryMap().entrySet()) {
            accessory = SGCommonProto.Accessory.newBuilder();
            accessory.setId(entry.getValue().id);
            accessory.setIntensifyLv(entry.getValue().getLv());
            accessory.setCurrentExp(entry.getValue().getExp());
            accessory.setUpLv(entry.getValue().upLv);
            cardInfo.addAccessory(accessory);
        }
        // 装备
        for (Map.Entry<Integer, EquipDB> entry : cardDB.getEquipMap().entrySet()) {
            equip = SGCommonProto.Equip.newBuilder();
            equip.setId(entry.getValue().id);
            equip.setLv(entry.getValue().getLv());
            cardInfo.addEquip(equip);
        }
        // 宿命列表
        cardInfo.addAllActiveFateList(cardDB.getActiveFateList());
        b.setCardInfo(cardInfo);
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Bag_CardDetail_VALUE, b.build().toByteArray());
    }

    /**
     * 装备一键强化
     *
     * @param playerController
     * @param cardId
     */
    public void equipIntensifyOneKey(PlayerController playerController, int cardId) {
        // 模块是否开启
        if (!CoreUtils.isFunctionUnLock(FunctionFactory.FUNCTION_ONE_KEY_STRENGTH, player)) {
            return;
        }

        CardDB cardDB = cardMap.get(cardId);
        if (notingError(playerController, cardDB)) {
            return;
        }
        SGBagProto.S2C_EquipIntensifyOneKey.Builder b = SGBagProto.S2C_EquipIntensifyOneKey.newBuilder();
        b.setCardId(cardId);

        EquipDB equipDB = null;
        TwoTuple<Boolean, String> result = new TwoTuple<>();
        // 一键强化
        boolean notify = false;
        for (Map.Entry<Integer, EquipDB> entry : cardDB.getEquipMap().entrySet()) {
            // 获取当前身上某位置的装备
            equipDB = cardDB.getEquipDB(entry.getKey());
            if (equipDB == null) {
                playerController.sendWarn(WordFactory.CARD_NOTHING_ERROR);
                return;
            }

            // 循环的次数是最高等级 - 当前等级
            int loop = DataFactory.getInstance().getDataSize(DataFactory.EQUIP_INTENSIFY_KEY) - equipDB.getLv();
            for (int i = 0; i < loop; i++) {
                equipIntensifyOneLevel(playerController, equipDB, entry.getKey(), result);
                if (!result.getFirst()) {
                    if (result.getSecond() != null) {
                        // playerController.sendWarn(result.getSecond());
                    }
                    break;
                }
                notify = true;
            }

            EquipIntensifyGroup.Builder equipIntensifyGroup = EquipIntensifyGroup.newBuilder();
            equipIntensifyGroup.setEquipType(SGCommonProto.E_EQUIP_TYPE.forNumber(entry.getKey()));
            equipIntensifyGroup.setEquipLv(equipDB.getLv());
            b.addGroups(equipIntensifyGroup);
        }

        if (notify) {
            // 修改战斗力
            if (cardDB.battle)
                calculateLegionChinaResult(E_LegionChinaType.EQUIP_INTENSIFY, playerController);
            else
                cardDB.updateFC();
        }
        // 通知客户端更新
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Bag_EquipIntensifyOneKey_VALUE, b.build().toByteArray());
    }

    /**
     * 装备强化
     *
     * @param playerController
     * @param cardId
     * @param type
     * @param count
     */
    public void equipIntensify(PlayerController playerController, int cardId, int type, int count) {
        CardDB cardDB = cardMap.get(cardId);
        if (notingError(playerController, cardDB)) {
            return;
        }

        EquipDB equipDB = null;
        TwoTuple<Boolean, String> result = new TwoTuple<>();
        // 获取当前身上某位置的装备
        equipDB = cardDB.getEquipDB(type);
        if (equipDB == null) {
            playerController.sendWarn(WordFactory.CARD_NOTHING_ERROR);
            return;
        }

        boolean notify = false;
        for (int i = 0; i < count; i++) {
            equipIntensifyOneLevel(playerController, equipDB, type, result);
            if (!result.getFirst()) {
                if (result.getSecond() != null) {
                    // playerController.sendWarn(result.getSecond());
                }
                break;
            }
            notify = true;
        }

        if (notify) {
            // 修改战斗力
            if (cardDB.battle)
                calculateLegionChinaResult(E_LegionChinaType.EQUIP_INTENSIFY, playerController);
            else
                cardDB.updateFC();

            SGBagProto.S2C_EquipIntensify.Builder b = SGBagProto.S2C_EquipIntensify.newBuilder();
            b.setCardId(cardId);
            b.setEquipType(SGCommonProto.E_EQUIP_TYPE.forNumber(type));
            b.setEquipLv(equipDB.getLv());
            playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Bag_EquipIntensify_VALUE, b.build().toByteArray());
        }
    }

    /**
     * 装备强化(强化1级)
     *
     * @param playerController
     * @param equipDB
     * @param type
     * @param result
     */
    private void equipIntensifyOneLevel(PlayerController playerController, EquipDB equipDB, int type,
                                        TwoTuple<Boolean, String> result) {
        result.setFirst(true);
        result.setSecond(null);

        // 下一级配置信息是否存在
        EquipIntensifyConfig nextLevelConfig = DataFactory.getInstance().getGameObject(DataFactory.EQUIP_INTENSIFY_KEY,
                equipDB.getLv() + 1);
        if (nextLevelConfig == null) {
            result.setFirst(false);
            result.setSecond(WordFactory.EQUIPMENT_STRENGTHENING_OVERRUN);
            return;
        }
        // 装备等级不能大于主将等级的两倍
        if (nextLevelConfig.id > playerController.getPlayer().getLv() * ConstantFactory.MAX_PLAYER_LV_RATE) {
            result.setFirst(false);
            result.setSecond(WordFactory.EQUIP_NOT_GREATER_THAN_PLAYER_LV);
            return;
        }

        // 当前等级
        GoodsData goodsData = null;
        for (GoodsData g : nextLevelConfig.needAssets) {
            if (g.type == type) {
                goodsData = g;
                break;
            }
        }
        if (goodsData == null) {
            result.setFirst(false);
            result.setSecond(WordFactory.EQUIPMENT_STRENGTHENING_OVERRUN);
            return;
        }

        // 资源是否足够
        if (bagInfo.getAsset(goodsData.id) < goodsData.value) {
            result.setFirst(false);
            result.setSecond(WordFactory.ASSET_NOT_ENOUGH);
            return;
        }
        // 扣除资源
        bagInfo.addAsset(goodsData.id, -goodsData.value);
        // 强化升级
        equipDB.lvUp(1);

        // 检测任务是否完成
        playerController.getPlayer().getExtInfo(TaskInfo.class).check(TaskFactory.TASK_TARAGET_MAIN_EQUIPINTENSIFY, 1);
        playerController.getPlayer().getExtInfo(TaskInfo.class).check(TaskFactory.TASK_TARAGET_EQUIPINTENSIFY, 0);
    }

    /**
     * 装备合成
     *
     * @param playerController
     * @param cardId
     * @param type
     */
    public void equipSyn(PlayerController playerController, int cardId, int type) {

        CardDB cardDB = cardMap.get(cardId);
        if (notingError(playerController, cardDB)) {
            return;
        }

        // 获取当前身上某位置的装备
        EquipDB equipDB = cardDB.getEquipDB(type);
        if (equipDB == null) {
            playerController.sendWarn(WordFactory.CARD_NOTHING_ERROR);
            return;
        }
        // 获取装备配置
        EquipConfig equip = equipDB.getConfig();

        EquipConfig nextEquip = DataFactory.getInstance().getGameObject(DataFactory.EQUIP_KEY, equip.nextEquip);
        if (nextEquip == null) {
            playerController.sendWarn(WordFactory.EQUIP_UPGRADED_HIGHEST_LEVEL);
            return;
        }

        // 检测资源是否足够
        List<GoodsData> list = new ArrayList<>();
        for (GoodsData goodsData : nextEquip.synNeed) {
            if (bagInfo.getGoodsCount(goodsData.type, goodsData.id) < goodsData.value) {
                if (goodsData.type == SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_PROPS_VALUE) {
                    BagInfo bagInfo = playerController.getPlayer().getExtInfo(BagInfo.class);
                    GoodsData[] result = bagInfo.rechargIfItemNotEnghou(goodsData);
                    if (result == null) {
                        playerController.sendWarn(WordFactory.GOODS_NOT_ENOUGH, goodsData.id);
                        return;
                    }
                    list.addAll(Arrays.asList(result));
                } else if (goodsData.type == SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_ASSETS_VALUE) {
                    playerController.sendWarn(WordFactory.ASSET_NOT_ENOUGH, goodsData.id);
                    return;
                } else if (goodsData.type == SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_CARDS_VALUE) {
                    playerController.sendWarn(WordFactory.CARD_FRAGMENT_ARE_NOT_ENOUGH);
                    return;
                }
            }else{
                list.add(goodsData);
            }
        }

        // 扣除资源
        for (GoodsData data : list) {
            bagInfo.subGoods(data);
        }

        // 装备合成后记录合成的次数
        equipDB.upCount += 1;

        // 合成之后新的装备赋值
        equipDB.setId(nextEquip.id);

        // 修改战斗力
        if (cardDB.battle)
            calculateLegionChinaResult(E_LegionChinaType.EQUIP_MERGE, playerController);
        else
            cardDB.updateFC();

        // 检测任务是否完成
        playerController.getPlayer().getExtInfo(TaskInfo.class).check(TaskFactory.TASK_TARAGET_MAIN_EQUIPSYN, 1);
        //检测开服活动是否完成
        playerController.getPlayer().getSevenDayData().checkAllRewardState(SevenDayFactory.EVENT_TYPE_10,1,equipDB.upCount +1);


        SGBagProto.S2C_EquipUp.Builder b = SGBagProto.S2C_EquipUp.newBuilder();
        b.setCardId(cardId);
        b.setEquipType(SGCommonProto.E_EQUIP_TYPE.forNumber(type));
        b.setNextEquipId(nextEquip.id);

        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Bag_EquipUp_VALUE, b.build().toByteArray());

        // 是否弹出资源不足
        nextEquip = DataFactory.getInstance().getGameObject(DataFactory.EQUIP_KEY, equipDB.getConfig().nextEquip);
        if (nextEquip == null) {
            return;
        }

        // 检测任务
        playerController.getPlayer().getExtInfo(TaskInfo.class).check(TaskFactory.TASK_TARAGET_EVERYDAY_SYNC, 0);

        for (GoodsData data : nextEquip.synNeed) {
            // 材料不足，弹出限时折扣活动，这里要过滤掉货币只校验资源
            if (data.type == SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_PROPS_VALUE
                    && bagInfo.getGoodsCount(data.type, data.id) < data.value) {
                FlashSaleRecord fsr = playerController.getPlayer().getBonusData().check(playerController,
                        E_FlashSaleType.EQUIP_COMPOSE);
                if (fsr != null) {
                    playerController.sendMsg(SGMainProto.E_MSG_ID.MSGID_Player_PushFlashSale_VALUE,
                            SGPlayerProto.S2C_PushFlashSale.newBuilder()
                                    .setSaleObject(SGCommonProto.KeyListObject.newBuilder().setKey(fsr.id)
                                            .setValue((int) (fsr.endTime - DataFactory.currentTime)))
                                    .build().toByteArray());
                }
                return;
            }
        }
    }

    /**
     * 饰品激活
     *
     * @param playerController
     * @param cardId
     * @param type
     */
    public void accessoryActivated(PlayerController playerController, int cardId, int type) {
        SGBagProto.S2C_AccessoryActivated.Builder b = SGBagProto.S2C_AccessoryActivated.newBuilder();
        CardDB cardDB = cardMap.get(cardId);
        if (notingError(playerController, cardDB)) {
            return;
        }

        // 获取当前身上某位置的饰品
        AccessoryDB accessoryDB = cardDB.getAccessoryDB(type);
        if (accessoryDB == null) {
            playerController.sendWarn(WordFactory.OBJECT_NOT_EXIST);
            return;
        }
        // 检测是否已激活
        if (accessoryDB.isActivated) {
            playerController.sendWarn(WordFactory.ACCESSORY_HAS_BEEN_ACTIVATED);
            return;
        }

        AccessoryConfig accessoryConfig = DataFactory.getInstance().getGameObject(DataFactory.ACCESSORY_KEY,
                accessoryDB.id);
        if (accessoryConfig == null) {
            playerController.sendWarn(WordFactory.CONFIG_NOT_EXIST);
            return;
        }
        // 检测所需的资源是否足够
        if (accessoryConfig.checkNeedGoods(bagInfo, playerController)) {
            return;
        }

        // 激活扣除背包资源
        for (GoodsData goodsData : accessoryConfig.activate) {
            if (goodsData.type == SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_PROPS_VALUE) {
                bagInfo.addProp(goodsData.id, -goodsData.value);
                break;
            } else if (goodsData.type == SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_ASSETS_VALUE) {
                bagInfo.addAsset(goodsData.id, -goodsData.value);
                break;
            } else if (goodsData.type == SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_CARDS_VALUE) {
                bagInfo.addCard(goodsData.id, -goodsData.value);
                break;
            }
        }
        accessoryDB.isActivated = true;

        b.setAccessoryType(SGCommonProto.E_ACCESSORY_TYPE.forNumber(type));
        b.setCardId(cardId);
        b.setIsActivated(accessoryDB.isActivated);
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Bag_AccessoryActivated_VALUE, b.build().toByteArray());

        playerController.updateFC();
    }

    /**
     * 饰品强化
     *
     * @param playerController
     * @param cardId
     * @param type
     */
    public void accessoryIntensify(PlayerController playerController, int cardId, int type) {
        CardDB cardDB = cardMap.get(cardId);
        if (notingError(playerController, cardDB)) {
            return;
        }
        // 获取当前身上某位置的饰品
        AccessoryDB accessoryDB = cardDB.getAccessoryDB(type);
        if (accessoryDB == null) {
            playerController.sendWarn(WordFactory.CARD_NOTHING_ERROR);
            return;
        }

        // 饰品强化
        AccessoryIntensifyConfig accessoryIntensifyConfig = DataFactory.getInstance()
                .getGameObject(DataFactory.ACCESSORY_INTENSIFY_KEY, accessoryDB.getLv() + 1);
        if (accessoryIntensifyConfig == null) {
            // 已到最高级别无法在升级
            playerController.sendWarn(WordFactory.EQUIP_INTENSIFY_HIGHEST_LEVEL);
            return;
        }

        if (cardDB.star < accessoryIntensifyConfig.unlockLevel) {
            // 饰品等级不能超过卡牌星级
            playerController.sendWarn(WordFactory.CARD_STAR_ACHIEVE_ACCESSORY_LEVEL,
                    accessoryIntensifyConfig.unlockLevel);
            return;
        }

        // 计算后的所需经验和升级所加等级
        int array[] = getUpLv(null, cardDB, accessoryIntensifyConfig, accessoryDB);

        // 检测背包里的经验道具是否足够
        List<PropDB> expProps = bagInfo.getPropTypeMap().get(ConstantFactory.PROP_TYPE_ACCESSORY_EXP);
        long tempExp = getExpValue(array, expProps);
        if (tempExp < array[0]) {
            // 材料不够，轻先获取材料
            playerController.sendWarn(WordFactory.EXPERIENCE_PROPS_ARE_NOT_ENOUGH);
            return;
        }

        // 根据经验值，由小到大排序
        Collections.sort(expProps, new Comparator<PropDB>() {
            @Override
            public int compare(PropDB o1, PropDB o2) {
                return new Integer(o1.getConfig().effectValue).compareTo(o2.getConfig().effectValue);
            }
        });

        // 扣除大于needExp的道具
        Map<Integer, Integer> tempMap = tempMap(array[0], expProps);

        // 扣除经验卷轴,并获取要添加的总经验值
        int addTotalExp = 0;
        int size = tempMap.size();
        for (Map.Entry<Integer, Integer> entry : tempMap.entrySet()) {
            if (size > 1) {
                addTotalExp += bagInfo.getPropById(entry.getKey()).getConfig().effectValue * entry.getValue();
            } else {
                addTotalExp = bagInfo.getPropById(entry.getKey()).getConfig().effectValue * entry.getValue();
            }
            bagInfo.addProp(entry.getKey(), -entry.getValue());
        }

        accessoryDB.addExp(addTotalExp);

        // 修改战斗力
        if (cardDB.battle)
            calculateLegionChinaResult(E_LegionChinaType.ACCESSORY_INTENSIFY, playerController);
        else
            cardDB.updateFC();

        SGBagProto.S2C_AccessoryIntensify.Builder b = SGBagProto.S2C_AccessoryIntensify.newBuilder();
        b.setCardId(cardId);
        b.setAccessoryType(SGCommonProto.E_ACCESSORY_TYPE.forNumber(type));
        b.setAccessoryLv(accessoryDB.getLv());
        // 当前经验
        b.setCurrentExp(accessoryDB.getExp());
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Bag_AccessoryIntensify_VALUE, b.build().toByteArray());

        // 检测任务是否完成
        playerController.getPlayer().getExtInfo(TaskInfo.class).check(TaskFactory.TASK_TARAGET_MAIN_ACCESSORY_INTENSIFY,
                1);
        playerController.getPlayer().getExtInfo(TaskInfo.class).check(TaskFactory.TASK_TARAGET_EVERYDAY_SHIPIN, 0);
    }

    public long getExpValue(int array[], List<PropDB> expProps) {
        long tempExp = 0;
        if (expProps != null) {
            if (array[0] > 0) {
                for (PropDB prop : expProps) {
                    tempExp += prop.getConfig().effectValue * prop.count;
                }
            }
        }
        return tempExp;
    }

    /**
     * 饰品进阶
     */
    public void accessoryUp(PlayerController playerController, int cardId, int type) {

        CardDB cardDB = cardMap.get(cardId);
        if (notingError(playerController, cardDB)) {
            return;
        }

        // 获取当前身上某位置的饰品
        AccessoryDB accessoryDB = cardDB.getAccessoryDB(type);
        AccessoryConfig accessory = accessoryDB.getConfig();

        // 饰品进阶
        AccessoryUpConfig nextAccessory = DataFactory.getInstance().getGameObject(DataFactory.ACCESSORY_UP_KEY,
                accessoryDB.upLv + 1);

        if (nextAccessory == null) {
            // 已经到最高级别无法升级
            playerController.sendWarn(WordFactory.ACCESSORY_UPGRADED_HIGHEST_LEVEL);
            return;
        }
        if (cardDB.star < nextAccessory.unlockLevel) {
            // 饰品等级不能超过玩家等级
            playerController.sendWarn(WordFactory.ORNAMENTS_NEED_CARD_STAR_IN_ADVANCE, nextAccessory.unlockLevel);
            return;
        }
        // 检测背包的资源是否足够
        TwoTuple<Boolean, Integer> checkResult = nextAccessory.checkEnoughProp(bagInfo, accessory.quality);
        if (!checkResult.getFirst()) {
            // 需要进阶的材料不够，轻先获取材料
            playerController.sendWarn(WordFactory.GOODS_NOT_ENOUGH, checkResult.getSecond());
            return;
        }
        // 扣除背包中的资源
        for (int i = 0; i < nextAccessory.needProps.length; i++) {
            // 品质
            if (accessory.quality == nextAccessory.needProps[i].type) {
                bagInfo.addProp(nextAccessory.needProps[i].id, -nextAccessory.needProps[i].value);
                break;
            }
        }

        // 下一级
        accessoryDB.upLv++;

        // 修改战斗力
        if (cardDB.battle)
            calculateLegionChinaResult(E_LegionChinaType.ACCESSORY_QUALITY, playerController);
        else
            cardDB.updateFC();

        SGBagProto.S2C_AccessoryUp.Builder b = SGBagProto.S2C_AccessoryUp.newBuilder();
        b.setCardId(cardId);
        b.setAccessoryType(SGCommonProto.E_ACCESSORY_TYPE.forNumber(type));
        b.setAccessoryLvId(accessoryDB.upLv);

        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Bag_AccessoryUp_VALUE, b.build().toByteArray());

        // 材料不足弹出限时促销活动
        nextAccessory = DataFactory.getInstance().getGameObject(DataFactory.ACCESSORY_UP_KEY, accessoryDB.upLv + 1);
        if (nextAccessory == null) {
            return;
        }
        checkResult = nextAccessory.checkEnoughProp(bagInfo, accessory.quality);
        if (!checkResult.getFirst()) {
            // 材料不足，弹出限时折扣活动
            FlashSaleRecord fsr = playerController.getPlayer().getBonusData().check(playerController,
                    E_FlashSaleType.ORNAMENT_LEVEL_UP);
            if (fsr != null) {
                playerController.sendMsg(SGMainProto.E_MSG_ID.MSGID_Player_PushFlashSale_VALUE,
                        SGPlayerProto.S2C_PushFlashSale.newBuilder()
                                .setSaleObject(SGCommonProto.KeyListObject.newBuilder().setKey(fsr.id)
                                        .setValue((int) (fsr.endTime - DataFactory.currentTime)))
                                .build().toByteArray());
            }
        }

        // 检测任务
        playerController.getPlayer().getExtInfo(TaskInfo.class).check(TaskFactory.TASK_TARAGET_EVERYDAY_SHIPIN_SHENGJIE,
                0);

        //检测开服活动是否完成
        playerController.getPlayer().getSevenDayData().checkAllRewardState(SevenDayFactory.EVENT_TYPE_11,1, accessoryDB.upLv);

    }

    /**
     * 根据经验卷轴id添加经验
     *
     * @param playerController
     * @param expId
     * @param count
     */
    public void accessoryAddExp(PlayerController playerController, int cardId, int expId, int count, int type) {
        count = count < 1 ? 1 : count;
        CardDB cardDB = cardMap.get(cardId);
        if (notingError(playerController, cardDB)) {
            return;
        }

        // 获取当前身上某位置的饰品
        AccessoryDB accessoryDB = cardDB.getAccessoryDB(type);
        int beforeLv = accessoryDB.getLv();

        // 获取配置文件中的经验卷轴
        PropConfig prop = DataFactory.getInstance().getGameObject(DataFactory.PROP_KEY, expId);
        if (prop == null) {
            // 获取经验卷轴配置错误
            playerController.sendWarn(WordFactory.EXPERIENCE_PROPS_IS_NULL);
            return;
        }
        // 所需总经验
        int sumExp = prop.effectValue * count;
        int bagExp = 0;
        // 检测背包里的经验道具是否足够
        List<PropDB> expProps = bagInfo.getPropTypeMap().get(ConstantFactory.PROP_TYPE_ACCESSORY_EXP);
        for (PropDB propConfig : expProps) {
            if (propConfig.id == expId) {
                bagExp += propConfig.getConfig().effectValue;
                break;
            }
        }

        if (bagExp < sumExp) {
            // 经验道具不足够，请获取经验道具
            playerController.sendWarn(WordFactory.EXPERIENCE_PROPS_ARE_NOT_ENOUGH);
            return;
        }

        // 扣除经验道具
        bagInfo.addProp(expId, -count);

        // 卡牌升级添加经验值
        accessoryDB.addExp(sumExp);
        int afterLv = accessoryDB.getLv();
        // 修改战斗力
        if (cardDB.battle) {
            if (beforeLv != afterLv) {
                calculateLegionChinaResult(E_LegionChinaType.ACCESSORY_INTENSIFY, playerController);
            }
        } else
            cardDB.updateFC();

        // if(afterLv - beforeLv >= 1){
        // //任务检测
        // TaskInfo taskInfo = playerController.getPlayer().getExtInfo(TaskInfo.class);
        //
        // List<TaskDB> doingList =
        // taskInfo.getDoingTask(ConstantFactory.TASK_TARAGET_MAIN_ACCESSORY_INTENSIFY);
        // for(TaskDB taskDB : doingList) {
        // taskDB.check(ConstantFactory.TASK_TARAGET_MAIN_ACCESSORY_INTENSIFY, 1);
        // }
        // List<TaskDB> everyList =
        // taskInfo.getDoingEveryTask(ConstantFactory.TASK_TARAGET_MAIN_ACCESSORY_INTENSIFY);
        // for(TaskDB taskDB : everyList) {
        // if(taskDB.status == SGCommonProto.E_TASK_STATUS.TASK_STATUS_UNDERWAY_VALUE){
        // taskDB.check(ConstantFactory.TASK_TARAGET_MAIN_ACCESSORY_INTENSIFY, 1);
        // }
        // }
        // }

        SGBagProto.S2C_AccessoryAddExp.Builder b = SGBagProto.S2C_AccessoryAddExp.newBuilder();
        b.setCardId(cardId);
        b.setCurrentExp(accessoryDB.getExp());
        b.setAccessoryLv(accessoryDB.getLv());
        b.setAccessoryType(SGCommonProto.E_ACCESSORY_TYPE.forNumber(type));
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Bag_AccessoryAddExp_VALUE, b.build().toByteArray());

    }

    /**
     * 宿命列表
     *
     * @param playerController
     */
    public void cardFateList(PlayerController playerController, int cardId) {
        CardDB cardDB = cardMap.get(cardId);
        if (cardDB == null) {
            // 卡牌不存在
            playerController.sendWarn(WordFactory.CARD_NOTHING_ERROR);
            return;
        }
        // 返回宿命列表
        SGBagProto.S2C_CardFateList.Builder b = SGBagProto.S2C_CardFateList.newBuilder();
        b.addAllFateList(cardDB.getActiveFateList());
        b.setCardId(cardId);

        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Bag_CardFateList_VALUE, b.build().toByteArray());

    }

    /**
     * 激活宿命
     *
     * @param playerController
     * @param cardId
     * @param fateId
     */
    public void cardFate(PlayerController playerController, int cardId, int fateId) {
        CardDB cardDB = cardMap.get(cardId);
        if (notingError(playerController, cardDB)) {
            return;
        }

        CardFateConfig cardFateConfig = DataFactory.getInstance().getGameObject(DataFactory.CARD_FATE_KEY, fateId);
        if (cardFateConfig == null) {
            // 此宿命配置不存在
            playerController.sendWarn(WordFactory.CARD_FATE_NOT_EXIST);
            return;
        }

        // 检测是否已激活此宿命
        if (cardDB.isHaveFate(fateId)) {
            // 已经激活过了
            playerController.sendWarn(WordFactory.CARD_FATE_HAS_BEEN_ACTIVATED);
            return;
        }

        // 这里是检测我是否拥有此宿命所需要的卡
        if (!cardFateConfig.checkNeedCards(bagInfo)) {
            // 此卡牌不在此宿命列表中
            playerController.sendWarn(WordFactory.CARD_NOT_FATE_LIST);
            return;
        }

        // 激活宿命
        cardDB.addFate(fateId);
        // 修改战斗力
        if (cardDB.battle)
            playerController.updateFC();

        SGBagProto.S2C_CardFate.Builder c = SGBagProto.S2C_CardFate.newBuilder();
        c.setCardId(cardId);
        c.addAllFateList(cardDB.getActiveFateList());
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Bag_CardFate_VALUE, c.build().toByteArray());

    }

    /**
     * 卡牌升星
     *
     * @param playerController
     * @param cardId
     */
    public void cardStar(PlayerController playerController, int cardId) {
        CardDB cardDB = cardMap.get(cardId);
        if (cardDB == null) {
            // 卡牌不存在
            playerController.sendWarn(WordFactory.CARD_NOTHING_ERROR);
            return;
        }

        StableDataConfig stableDataConfig = DataFactory.getInstance().getGameObject(DataFactory.STABLE_DATA_KEY,
                E_StableDataType.CARD_START.getCode());
        if (stableDataConfig == null) {
            playerController.sendWarn(WordFactory.PARAM_ERROR);
            return;
        }
        GoodsData good = stableDataConfig.getGoodsDataByQualiyu(cardDB.getQuality());

        // 判断玩家要升的星 是否达到上限
        if (good == null || (cardDB.star + 1) > good.value) {
            playerController.sendWarn(WordFactory.CARD_UPGRADED_HIGHEST_LEVEL);
            return;
        }

        // 获取下一个等级的卡牌
        CardStarConfig nextCardStarConfig = DataFactory.getInstance().getGameObject(DataFactory.CARD_STAR_KEY,
                cardDB.star + 1);
        if (nextCardStarConfig == null) {
            playerController.sendWarn(WordFactory.CARD_UPGRADED_HIGHEST_LEVEL);
            return;
        }

        if (cardDB.getLv() < nextCardStarConfig.unlockLevel) {
            // 需要卡牌等级
            playerController.sendWarn(WordFactory.HERO_ASCENDING_STARS, nextCardStarConfig.unlockLevel);
            return;
        }

        CardConfig cardConfig = cardDB.getConfig();

        // 检查背包理所需要的资源是否足够
        TwoTuple<Boolean, Integer> checkResult = nextCardStarConfig.checkAsset(bagInfo, cardConfig.quality);
        if (!checkResult.getFirst()) {
            // 背包中所需资源不够
            playerController.sendWarn(WordFactory.ASSET_NOT_ENOUGH, checkResult.getSecond());
            return;
        }
        // 检查背包中所需的兵种碎片
        if (!nextCardStarConfig.checkDebris(bagInfo, cardConfig.quality, cardConfig.lvUpProp)) {
            // 背包中碎片不足
            playerController.sendWarn(WordFactory.BAG_LVUPPROP_ARE_NOT_ENOUGH);
            return;
        }

        // 检测所需要的突破令是否足够
        checkResult = nextCardStarConfig.checkProps(bagInfo, cardConfig.quality);
        if (!checkResult.getFirst()) {
            // 突破令不够
            playerController.sendWarn(WordFactory.GOODS_NOT_ENOUGH, checkResult.getSecond());
            return;
        }

        // 扣除背包中的资源
        CommonData asset = nextCardStarConfig.needAssets.get(cardConfig.quality);
        if (asset != null)
            bagInfo.addAsset(asset.id, -asset.value);
        // for(Map.Entry<Integer,CommonData> entry :
        // nextCardStarConfig.needAssets.entrySet()){
        // if(entry.getKey() == cardConfig.quality){
        // bagInfo.addAsset(entry.getValue().id, -entry.getValue().value);
        // break;
        // }
        // }
        // 扣除碎片
        for (int i = 0; i < nextCardStarConfig.needDebris.length; i++) {
            if (cardConfig.quality == nextCardStarConfig.needDebris[i].type
                    && nextCardStarConfig.needDebris[i].value > 0) {
                bagInfo.addProp(cardConfig.lvUpProp, -nextCardStarConfig.needDebris[i].value);
                break;
            }
        }

        // 扣除背包中的道具突破令
        CommonData tupo = nextCardStarConfig.needProps.get(cardConfig.quality);
        if (tupo != null)
            bagInfo.addProp(tupo.id, -tupo.value);
        // bagInfo.addProp(nextCardStarConfig.needProps.get(cardConfig.quality))
        // for(Map.Entry<Integer,CommonData> entry :
        // nextCardStarConfig.needProps.entrySet()){
        // if(entry.getKey() == cardConfig.quality){
        // bagInfo.addProp(entry.getValue().id, -entry.getValue().value);
        // break;
        // }
        // }
        // 星级加1
        cardDB.addStar(1);

        if (cardDB.battle)
            calculateLegionChinaResult(E_LegionChinaType.HERO_STAR, playerController);
        else
            cardDB.updateFC();

        String content;
        if (!Utils.isNullOrEmpty(content = NoticeUtils.getScrollNotice(E_ScrollNoticeType.HERO_STAR_UP,
                player.getName(), cardId, cardDB.star))) {
            // GameServer.getInstance().getWorldManager().dispatchGet(content);
            player.getChangeGoods().getNotices().add(content);
        }
        // 检测任务是否完成
        playerController.getPlayer().getExtInfo(TaskInfo.class).check(TaskFactory.TASK_TARAGET_MAIN_CARD_STAR, 1);
        playerController.getPlayer().getExtInfo(TaskInfo.class).check(TaskFactory.TASK_TARAGET_EVERYDAY_HERO_STAR, 0);

        //检测开服活动是否完成
        playerController.getPlayer().getSevenDayData().checkAllRewardState(SevenDayFactory.EVENT_TYPE_12,1,cardDB.star);
        playerController.getPlayer().getSevenDayData().checkAllRewardState(SevenDayFactory.EVENT_TYPE_24,1,cardDB.star,cardDB.getQuality());

        SGBagProto.S2C_CardUpStar.Builder b = SGBagProto.S2C_CardUpStar.newBuilder();
        b.setCardId(cardId);
        b.setCardStarId(cardDB.star);
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Bag_CardUpStar_VALUE, b.build().toByteArray());

        // 判断下一级升星所需要的英雄纹章是否足够
        nextCardStarConfig = DataFactory.getInstance().getGameObject(DataFactory.CARD_STAR_KEY, cardDB.star + 1);
        if (nextCardStarConfig == null) {
            // 无法升级
            return;
        }
        checkResult = nextCardStarConfig.checkProps(bagInfo, cardConfig.quality);
        if (!checkResult.getFirst()) {
            // 是否弹出英雄纹章的促销活动
            FlashSaleRecord fsr = playerController.getPlayer().getBonusData().check(playerController,
                    E_FlashSaleType.CARD_LEVEL_UP);
            if (fsr != null) {
                playerController.sendMsg(SGMainProto.E_MSG_ID.MSGID_Player_PushFlashSale_VALUE,
                        SGPlayerProto.S2C_PushFlashSale.newBuilder()
                                .setSaleObject(SGCommonProto.KeyListObject.newBuilder().setKey(fsr.id)
                                        .setValue((int) (fsr.endTime - DataFactory.currentTime)))
                                .build().toByteArray());
            }
        }
    }

    /***
     * 卡牌合成
     *
     * @param playerController
     * @param synId
     */
    public void cardSyn(PlayerController playerController, int synId) {

        // CardDB cardDB = getCard(synId);
        // if(notingError(playerController,cardDB)){
        // return;
        // }
        CardConfig cardConfig = DataFactory.getInstance().getGameObject(DataFactory.CARD_KEY, synId);
        if (cardConfig == null) {
            // 获取配置数据错误
            playerController.sendWarn(WordFactory.CARD_NOTHING_ERROR);
            return;
        }
        // 检测背包碎片道具是否足够
        if (bagInfo.getPropCount(synId) < cardConfig.transformation) {
            // 道具不够
            playerController.sendWarn(WordFactory.GOODS_NOT_ENOUGH, synId);
            return;
        }

        bagInfo.addCard(cardConfig.id, 1);
        bagInfo.addProp(synId, -cardConfig.transformation);

        // cardDB.updateFC();
        //
        // if(cardDB.battle)
        // playerController.updateFC();

        // 检测任务是否完成
        playerController.getPlayer().getExtInfo(TaskInfo.class).check(TaskFactory.TASK_TARAGET_CARD, 1);

        SGBagProto.S2C_CardSyn.Builder b = SGBagProto.S2C_CardSyn.newBuilder();
        b.setSynId(synId);
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Bag_CardSyn_VALUE, b.build().toByteArray());

    }

    /***
     * 卡牌升级
     *
     * @param playerController
     * @param cardId
     */
    public void cardLv(PlayerController playerController, int cardId, int needLv) {
        CardDB cardDB = cardMap.get(cardId);
        if (cardDB == null) {
            // 卡牌不存在
            playerController.sendWarn(WordFactory.CARD_NOTHING_ERROR);
            return;
        }

        CardLvConfig nextCardLvConfig = DataFactory.getInstance().getGameObject(DataFactory.CARD_LV_KEY,
                cardDB.getLv() + needLv);
        if (nextCardLvConfig == null) {
            // 已经到最高等级不能在升级
            playerController.sendWarn(WordFactory.CARD_UPGRADED_HIGHEST_LEVEL);
            return;
        }

        if (cardDB.getLv() >= playerController.getPlayer().getLv()) {
            // 卡牌等级不能大于等于主将等级
            playerController.sendWarn(WordFactory.CARD_NOT_GREATER_THAN_PLAYER_LV);
            return;
        }

        int array[] = getUpLv(nextCardLvConfig, cardDB, null, null);

        // 检测背包里的经验道具是否足够
        List<PropDB> expProps = bagInfo.getPropTypeMap().get(ConstantFactory.PROP_TYPE_CARD_EXP);
        long tempExp = getExpValue(array, expProps);

        if (tempExp < array[0]) {
            // 经验道具不足够，请获取经验道具
            playerController.sendWarn(WordFactory.EXPERIENCE_PROPS_ARE_NOT_ENOUGH);
            return;
        }

        // 根据经验值，由小到大排序
        Collections.sort(expProps, new Comparator<PropDB>() {
            @Override
            public int compare(PropDB o1, PropDB o2) {
                return new Integer(o1.getConfig().effectValue).compareTo(o2.getConfig().effectValue);
            }
        });

        // 扣除大于needExp的道具
        Map<Integer, Integer> tempMap = tempMap(array[0], expProps);

        // 扣除经验卷轴,并获取要添加的总经验值
        int addTotalExp = 0;
        int size = tempMap.size();
        for (Map.Entry<Integer, Integer> entry : tempMap.entrySet()) {
            if (size > 1) {
                addTotalExp += bagInfo.getPropById(entry.getKey()).getConfig().effectValue * entry.getValue();
            } else {
                addTotalExp = bagInfo.getPropById(entry.getKey()).getConfig().effectValue * entry.getValue();
            }
            bagInfo.addProp(entry.getKey(), -entry.getValue());
        }

        int beforeLv = cardDB.getLv();
        // 添加经验值
        cardDB.addExp(addTotalExp);
        int afterLv = cardDB.getLv();

        if (cardDB.battle) {
            if (beforeLv != afterLv) {
                calculateLegionChinaResult(E_LegionChinaType.HERO_LEVEL, playerController);
            }
        } else
            cardDB.updateFC();

        SGBagProto.S2C_CardUpLv.Builder b = SGBagProto.S2C_CardUpLv.newBuilder();
        b.setCardId(cardId);
        b.setCardLv(cardDB.getLv());
        b.setCurrentExp(cardDB.getExp());
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Bag_CardUpLv_VALUE, b.build().toByteArray());

        // 检测任务是否完成
        playerController.getPlayer().getExtInfo(TaskInfo.class).check(TaskFactory.TASK_TARAGET_MAIN_CARD_LV, 1);
        playerController.getPlayer().getExtInfo(TaskInfo.class).check(TaskFactory.TASK_TARAGET_EVERYDAY_CARD_LV, 1);
    }

    /**
     * 根据经验卷轴id添加经验
     *
     * @param playerController
     * @param expId
     * @param count
     */
    public void cardExp(PlayerController playerController, int cardId, int expId, int count) {
        count = count < 1 ? 1 : count;
        CardDB cardDB = cardMap.get(cardId);

        if (notingError(playerController, cardDB)) {
            return;
        }
        int beforeLv = cardDB.getLv();

        if (cardDB.getLv() >= playerController.getPlayer().getLv()) {

            // 卡牌等级不能大于等于主将等级
            playerController.sendWarn(WordFactory.CARD_NOT_GREATER_THAN_PLAYER_LV);
            return;
        }

        // 获取配置文件中的经验卷轴
        PropConfig prop = DataFactory.getInstance().getGameObject(DataFactory.PROP_KEY, expId);
        if (prop == null) {
            // 获取经验卷轴配置错误
            playerController.sendWarn(WordFactory.EXPERIENCE_PROPS_IS_NULL);
            return;
        }

        // 所需总经验
        int sumExp = prop.effectValue * count;
        int bagExp = 0;
        // 检测背包里的经验道具是否足够
        List<PropDB> expProps = bagInfo.getPropTypeMap().get(ConstantFactory.PROP_TYPE_CARD_EXP);
        for (PropDB propConfig : expProps) {
            if (propConfig.id == expId) {
                bagExp += propConfig.getConfig().effectValue;
                break;
            }
        }

        if (bagExp < sumExp) {
            // 经验道具不足够，请获取经验道具
            playerController.sendWarn(WordFactory.EXPERIENCE_PROPS_ARE_NOT_ENOUGH, expId);
            return;
        }

        // 扣除经验道具
        bagInfo.addProp(expId, -count);
        // 卡牌升级添加经验值
        cardDB.addExp(sumExp);
        int afterLv = cardDB.getLv();
        // 修改战斗力
        if (cardDB.battle)
            if (beforeLv != afterLv) {
                calculateLegionChinaResult(E_LegionChinaType.HERO_LEVEL, playerController);
            } else
                cardDB.updateFC();

        // 根据经验值来计算升级次数
        // if(afterLv - beforeLv >=1 ){
        //
        // //主线任务检测
        // TaskInfo taskInfo = playerController.getPlayer().getExtInfo(TaskInfo.class);
        // List<TaskDB> doingList =
        // taskInfo.getDoingTask(ConstantFactory.TASK_TARAGET_MAIN_CARD_LV);
        // for(TaskDB taskDB : doingList) {
        // taskDB.check(ConstantFactory.TASK_TARAGET_MAIN_CARD_LV, 1);
        // }
        //
        // //日常任务检测
        // List<TaskDB> everyList =
        // taskInfo.getDoingEveryTask(ConstantFactory.TASK_TARAGET_EVERYDAY_CARD_LV);
        // for(TaskDB taskDB : everyList) {
        // if(taskDB.status == SGCommonProto.E_TASK_STATUS.TASK_STATUS_UNDERWAY_VALUE){
        // taskDB.check(ConstantFactory.TASK_TARAGET_EVERYDAY_CARD_LV, 1);
        // }
        // }
        // }
        SGBagProto.S2C_CardAddExp.Builder b = SGBagProto.S2C_CardAddExp.newBuilder();
        b.setCardId(cardId);
        b.setCardLv(cardDB.getLv());
        b.setCurrentExp(cardDB.getExp());
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Bag_CardAddExp_VALUE, b.build().toByteArray());

    }

    /***
     * 卡牌升级，饰品强化返回所需的经验值和等级 0:needExp ,1:tempLv
     *
     * @param nextCardLvConfig
     * @return
     */
    /***
     * 卡牌升级，饰品强化返回所需的经验值和等级 0:needExp ,1:tempLv
     *
     * @param nextCardLvConfig
     * @return
     */
    public int[] getUpLv(CardLvConfig nextCardLvConfig, CardDB cardDB,
                         AccessoryIntensifyConfig accessoryIntensifyConfig, AccessoryDB accessoryDB) {

        int needExp = 0;
        int tempLv = 0;
        if (nextCardLvConfig != null && cardDB != null) {

            int totalExp = nextCardLvConfig.getTotalExp(cardDB.getConfig().quality);
            if (totalExp > cardDB.getExp()) {
                needExp = totalExp - cardDB.getExp();
            } else {
                int nextLvId = nextCardLvConfig.id;
                while (true) {
                    CardLvConfig nextLv = DataFactory.getInstance().getGameObject(DataFactory.CARD_LV_KEY,
                            nextLvId + 1);
                    if (nextLv.getTotalExp(cardDB.getConfig().quality) > cardDB.getExp()) {
                        break;
                    } else {
                        nextLvId++;
                        tempLv++;
                    }

                }
            }
        }
        if (accessoryIntensifyConfig != null && accessoryDB != null) {
            int totalExp = accessoryIntensifyConfig.getTotalExp(cardDB.getConfig().quality);
            if (totalExp > accessoryDB.getExp()) {
                needExp = totalExp - accessoryDB.getExp();
            } else {
                int nextLvId = accessoryIntensifyConfig.id;
                while (true) {
                    AccessoryIntensifyConfig nextLv = DataFactory.getInstance()
                            .getGameObject(DataFactory.ACCESSORY_INTENSIFY_KEY, nextLvId + 1);
                    if (nextLv.getTotalExp(cardDB.getConfig().quality) > accessoryDB.getExp()) {
                        break;
                    } else {
                        nextLvId++;
                        tempLv++;
                    }

                }
            }
        }
        int array[] = new int[2];
        array[0] = needExp;
        array[1] = tempLv;
        return array;
    }

    /**
     * 返回需要扣除的经验道具
     *
     * @param needExp
     * @param expProps
     * @return
     */
    public Map<Integer, Integer> tempMap(int needExp, List<PropDB> expProps) {

        // 扣除大于needExp的道具
        int sumExp = 0;
        // 要扣除的经验道具 key : id value: count
        Map<Integer, Integer> tempMap = new ConcurrentHashMap<>();
        if (needExp > 0) {
            if (expProps.size() > 0 && expProps.get(0).getConfig().effectValue >= needExp) {
                // 要扣除的map已存在 那么个数加1
                tempMap.put(expProps.get(0).id, 1);
            } else {
                choose:
                for (PropDB prop : expProps) {
                    // 根据经验卷轴id 计算总经验
                    for (int i = 0; i < prop.count; i++) {
                        sumExp += prop.getConfig().effectValue;
                        // 总经验值小于需要的经验值
                        if (needExp >= sumExp) {
                            // 要扣除的map已存在 那么个数加1
                            if (tempMap.get(prop.id) != null) {
                                tempMap.put(prop.id, tempMap.get(prop.id) + 1);
                            } else {
                                // 存入
                                tempMap.put(prop.id, 1);
                            }
                        } else {
                            if (sumExp - needExp < prop.getConfig().effectValue) {
                                if (tempMap.get(prop.id) != null) {
                                    tempMap.put(prop.id, tempMap.get(prop.id) + 1);
                                } else {
                                    tempMap.put(prop.id, 1);
                                }
                            }
                            break choose;

                        }

                    }
                }
            }

        }
        return tempMap;
    }

    /**
     * 卡牌升级 新需求：必须是能达到下一个5的整数倍才提示红点
     *
     * @return
     */
    public boolean checkCardUpLv() {
        if (!CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_CARD_UP_LV, player)) {
            return false;
        }

        CardLvConfig nextCardLvConfig = null;
        List<CardLvConfig> list = null;
        int maxLv = (list = DataFactory.getInstance().getDataList(DataFactory.CARD_LV_KEY)).get(list.size() - 1).id;
        for (CardDB cardDB : battleCardList) {
            int currentLv = cardDB.getLv();
            int nextLv = Math.min(CoreUtils.getNextMultNum(5, currentLv), maxLv);
            if (nextLv > player.getLv()) {
                continue;
            }
            nextCardLvConfig = DataFactory.getInstance().getGameObject(DataFactory.CARD_LV_KEY, nextLv);
            if (checkSingleCardUpLv(nextCardLvConfig.getTotalExp(cardDB.getConfig().quality) - cardDB.getExp()))
                return true;
        }
        return false;
    }

    /***
     * 检查单张卡牌升级
     *
     * @return
     */
    public boolean checkSingleCardUpLv(int needExp) {
        List<PropDB> expProps = null;
        // 检测背包里的经验道具是否足够
        expProps = bagInfo.getPropTypeMap().get(ConstantFactory.PROP_TYPE_CARD_EXP);
        int tempExp = 0;
        if (expProps != null) {
            if (needExp > 0) {
                for (PropDB prop : expProps) {
                    tempExp += prop.getConfig().effectValue * prop.count;
                }
                if (tempExp > needExp) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 英雄升星
     *
     * @return
     */
    public boolean checkCardUpStar() {
        if (!CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_CARD_UP_STAR, player)) {
            return false;
        }

        CardStarConfig nextCardStarConfig = null;
        StableDataConfig stableDataConfig = DataFactory.getInstance().getGameObject(DataFactory.STABLE_DATA_KEY,
                E_StableDataType.CARD_START.getCode());
        if (stableDataConfig == null) {
            return false;
        }
        GoodsData good = null;
        for (CardDB cardDB : battleCardList) {
            // 判断卡牌的品质 如果是紫卡 continue
            if (cardDB.getQuality() == ConstantFactory.QUALITY_PURPLE)
                continue;

            good = stableDataConfig.getGoodsDataByQualiyu(cardDB.getQuality());

            // 判断玩家要升的星 是否达到上限
            if (good == null || (cardDB.star + 1) > good.value) {
                continue;
            }
            // 获取下一个等级的卡牌
            nextCardStarConfig = DataFactory.getInstance().getGameObject(DataFactory.CARD_STAR_KEY, cardDB.star + 1);
            if (cardDB.getLv() < nextCardStarConfig.unlockLevel) {
                continue;
            }

            if (nextCardStarConfig != null) {
                // 检查背包中所需的资源,兵种碎片,突破令
                if (checkSingleCardUpStar(cardDB, nextCardStarConfig))
                    return true;

            }
        }

        return false;
    }

    /**
     * 单个英雄升星
     *
     * @return
     */
    public boolean checkSingleCardUpStar(CardDB cardDB, CardStarConfig nextCardStarConfig) {
        // 获取下一个等级的卡牌
        if (nextCardStarConfig == null) {
            nextCardStarConfig = DataFactory.getInstance().getGameObject(DataFactory.CARD_STAR_KEY, cardDB.star + 1);
        }
        if (nextCardStarConfig != null) {
            // 检查背包中所需的资源,兵种碎片,突破令
            CardConfig cardConfig = cardDB.getConfig();
            if (nextCardStarConfig.checkAsset(bagInfo, cardConfig.quality).getFirst()
                    && nextCardStarConfig.checkDebris(bagInfo, cardConfig.quality, cardConfig.lvUpProp)
                    && nextCardStarConfig.checkProps(bagInfo, cardConfig.quality).getFirst()) {
                return true;
            }
        }
        return false;
    }

    /***
     * 英雄宿命
     *
     * @return
     */
    public boolean checkSingleCardFate(CardDB cardDB) {
        List<Integer> tempList = new CopyOnWriteArrayList<>();
        tempList.addAll((cardDB.getConfig()).getFateList());
        // 得出所有未激活的宿命
        tempList.removeAll(cardDB.getActiveFateList());
        CardFateConfig cardFateConfig = null;
        for (Integer fateId : tempList) {
            cardFateConfig = DataFactory.getInstance().getGameObject(DataFactory.CARD_FATE_KEY, fateId);
            if (cardFateConfig.checkNeedCards(bagInfo))
                return true;
        }
        return false;
    }

    /***
     * 英雄宿命(检测是否有可激活的宿命)
     *
     * @return
     */
    public boolean checkCardFate() {
        if (!CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_CARD_FATE, player)) {
            return false;
        }

        for (CardDB cardDB : battleCardList) {
            // 每一张卡牌的宿命列表
            // 检测单张卡是否有可激活的宿命
            if (checkSingleCardFate(cardDB))
                return true;
        }
        return false;
    }

    /**
     * 装备强化
     *
     * @return
     */
    public boolean checkEquipIntensify() {
        if (!CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_EQUIP_INTENSIFY, player)) {
            return false;
        }

        for (CardDB cardDB : battleCardList) {
            // 获取当前所有得装备列表
            if (checkSingleEquipIntensify(cardDB))
                return true;
        }
        return false;
    }

    /**
     * 装备强化
     *
     * @return
     */
    public boolean checkSingleEquipIntensify(CardDB cardDB) {
        for (Map.Entry<Integer, EquipDB> entry : cardDB.getEquipMap().entrySet()) {
            // 获取配置
            if (checkEquipLevel(entry.getKey(), entry.getValue().getLv()))
                return true;
        }
        return false;
    }

    private boolean checkEquipLevel(int position, int equipLv) {
        int nextLv = CoreUtils.getNextMultNum(10, equipLv);
        if (nextLv > player.getLv() * ConstantFactory.MAX_PLAYER_LV_RATE) {
            return false;
        }

        List<EquipIntensifyConfig> list = null;
        int maxLv = (list = DataFactory.getInstance().getDataList(DataFactory.EQUIP_INTENSIFY_KEY))
                .get(list.size() - 1).id;
        nextLv = Math.min(nextLv, maxLv);
        EquipIntensifyConfig equipIntensifyConfig = null;
        List<GoodsData> totalConsume = new ArrayList<>();
        int index;
        // 计算总的升级消耗资源
        for (int i = 0; i < nextLv - equipLv; i++) {
            equipIntensifyConfig = DataFactory.getInstance().getGameObject(DataFactory.EQUIP_INTENSIFY_KEY,
                    equipLv + 1 + i);
            if (equipIntensifyConfig != null) {
                for (GoodsData data : equipIntensifyConfig.needAssets) {
                    if (data.type == position) {
                        index = totalConsume.indexOf(
                                new GoodsData(SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_ASSETS_VALUE, data.id, data.value));
                        if (index >= 0) {// 已经有了
                            totalConsume.get(index).value += data.value;
                        } else {
                            totalConsume.add(new GoodsData(SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_ASSETS_VALUE, data.id,
                                    data.value));
                        }
                    }

                }
            } else {
                break;
            }
        }

        // 计算资源是否满足
        for (GoodsData data : totalConsume) {
            if (bagInfo.getGoodsCount(data.type, data.id) < data.value) { // 已有的小于需要的
                return false;
            }
        }

        return true;
    }

    /***
     * 装备合成
     *
     * @return
     */
    public boolean checkEquipSynthesis() {
        if (!CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_EQUIP_SYN, player)) {
            return false;
        }

        for (CardDB cardDB : battleCardList) {
            // 获取当前身上某位置的装备
            if (checkSingleEquipSynthesis(cardDB))
                return true;
        }
        return false;
    }

    /***
     * 装备合成
     *
     * @return
     */
    public boolean checkSingleEquipSynthesis(CardDB cardDB) {
        EquipConfig equip = null;
        EquipConfig nextEquip = null;

        for (EquipDB equipDB : cardDB.getEquipMap().values()) {
            // 获取装备配置
            equip = equipDB.getConfig();
            nextEquip = DataFactory.getInstance().getGameObject(DataFactory.EQUIP_KEY, equip.nextEquip);
            if (nextEquip != null) {
                if (nextEquip.checkEnoughProp(bagInfo) && nextEquip.checkEnoughAsset(bagInfo)
                        && nextEquip.checkEnoughCard(bagInfo)) {
                    return true;
                }
            }
        }
        return false;
    }

    /***
     * 饰品强化
     *
     * @return
     */
    public boolean checkAccessoryIntensify() {
        if (!CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_ACCESSORY_ACTIVATION_UP_LV, player)) {
            return false;
        }

        /**
         * 计算总的经验道具的总值
         */
        List<PropDB> expProps = bagInfo.getPropTypeMap().get(ConstantFactory.PROP_TYPE_ACCESSORY_EXP);
        int totalExp = 0;
        if (expProps != null) {
            for (PropDB prop : expProps) {
                totalExp += prop.getConfig().effectValue * prop.count;
            }
        }
        for (CardDB cardDB : battleCardList) {

            if (cardDB.getQuality() == ConstantFactory.QUALITY_PURPLE)
                continue;
            if (checkSingleAccessoryIntensify(cardDB, totalExp))
                return true;
        }
        return false;
    }

    /***
     * 饰品强化
     *
     * @return
     */
    public boolean checkSingleAccessoryIntensify(CardDB cardDB, int totalExp) {
        AccessoryIntensifyConfig accessoryIntensifyConfig = null;
        for (AccessoryDB accessoryDB : cardDB.getAccessoryMap().values()) {
            if (!accessoryDB.isActivated) {
                continue;
            }
            // 饰品强化
            accessoryIntensifyConfig = DataFactory.getInstance().getGameObject(DataFactory.ACCESSORY_INTENSIFY_KEY,
                    accessoryDB.getLv() + 1);
            if (accessoryIntensifyConfig != null) {
                if (accessoryIntensifyConfig.id > player.getLv()) {
                    // 饰品等级不能超过玩家等级
                    continue;
                }

                // 解锁星级检测
                if (accessoryIntensifyConfig.unlockLevel > cardDB.star) {
                    continue;
                }
                int needExp = accessoryIntensifyConfig.getTotalExp(cardDB.getConfig().quality) - accessoryDB.getExp();
                // 检测背包里的经验道具是否足够
                // bagInfo = player.getExtInfo(BagInfo.class);

                if (totalExp > needExp) {
                    return true;
                }

            }
        }
        return false;
    }

    /***
     * 饰品进阶
     *
     * @return
     */
    public boolean checkAccessoryUp() {
        if (!CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_ACCESSORY_UP_LV, player)) {
            return false;
        }
        for (CardDB cardDB : battleCardList) {
            if (cardDB.getQuality() == ConstantFactory.QUALITY_PURPLE)
                continue;
            if (checkSingleAccessoryUp(cardDB))
                return true;
        }
        return false;
    }

    /***
     * 饰品进阶
     *
     * @return
     */
    public boolean checkSingleAccessoryUp(CardDB cardDB) {

        AccessoryDB accessoryDB = null;
        AccessoryConfig accessory = null;
        AccessoryUpConfig nextAccessory = null;
        for (Map.Entry<Integer, AccessoryDB> entry1 : cardDB.getAccessoryMap().entrySet()) {
            // 获取当前身上某位置的饰品
            accessoryDB = cardDB.getAccessoryDB(entry1.getKey().intValue());

            if (accessoryDB.upLv == 0)
                continue;

            accessory = accessoryDB.getConfig();
            // 饰品进阶
            nextAccessory = DataFactory.getInstance().getGameObject(DataFactory.ACCESSORY_UP_KEY, accessoryDB.upLv + 1);

            if (nextAccessory == null) {
                continue;
            }

            if (nextAccessory.unlockLevel > cardDB.star)
                continue;

            if (nextAccessory != null) {
                // 检测背包的资源是否足够
                if (nextAccessory.checkEnoughProp(bagInfo, accessory.quality).getFirst()) {
                    return true;
                }
            }
        }
        return false;
    }

    /***
     * 获取装备强化后等级
     *
     * @param equipLv
     * @return
     */
    public int getEquipIntensifyLv(int equipLv) {
        int count = 0;
        for (CardDB cardDB : battleCardList) {
            count += cardDB.getEquipLvCount(equipLv);
        }
        return count;
    }

    /**
     * 红点系统总入口检测
     *
     * @return
     */
    public boolean checkCorps() {
        // checkEquipIntensify();
        if (hasUnusedCard()) {
            return true;
        } else if (checkCardUpLv()) {
            return true;
        } else if (checkCardUpStar()) {
            return true;
        } else if (checkCardFate()) {
            return true;
        } else if (checkEquipIntensify()) {
            return true;
        } else if (checkEquipSynthesis()) {
            return true;
        } else if (checkAccessoryIntensify()) {
            return true;
        } else if (checkAccessoryUp()) {
            return true;
        } else if (checkUseLiquid()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检测吃药
     *
     * @return
     */
    private boolean checkUseLiquid() {
        if (!CoreUtils.isFunctionUnLock(FunctionFactory.FUNCTION_USE_LIQUID, player)) {
            return false;
        }
        List<PropDB> propDBs = bagInfo.getPropTypeMap().get(ConstantFactory.PROP_TYPE_LIQUID);
        if (propDBs == null || propDBs.isEmpty())
            return false;
        for (CardDB cardDB : battleCardList) {

            if (cardDB.getQuality() == ConstantFactory.QUALITY_PURPLE)
                continue;

            for (PropDB propDB : propDBs) {
                if (!cardDB.isUseLiquidTouchMax(propDB.id, 1)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 检测是否有未使用卡
     *
     * @return
     */
    private boolean hasUnusedCard() {
        // 计算自己最大的卡槽数量
        int maxBattleCount = getMaxCardSlotCount();
        int currentBattleCount = getBattleCardList().size();
        if (maxBattleCount > currentBattleCount && getSleepCardList().size() != 0) {
            return true;
        }
        return false;
    }

    // /***
    // * 军团列表没张卡牌红点检测
    // * @param cardDB
    // * @return
    // */
    // public boolean checkSingleCorps(CardDB cardDB){
    // if(checkSingleCardUpLv(cardDB, null)){
    // return true;
    // }else if(checkSingleCardUpStar(cardDB,null)){
    // return true;
    // }else if(checkSingleCardFate(cardDB)){
    // return true;
    // }else if(checkSingleEquipIntensify(cardDB)){
    // return true;
    // }else if(checkSingleEquipSynthesis(cardDB)){
    // return true;
    // }else if(checkSingleAccessoryIntensify(cardDB)){
    // return true;
    // }else if(checkSingleAccessoryUp(cardDB)){
    // return true;
    // }else {
    // return false;
    // }
    // }

    /***
     * 获取单个卡片信息
     *
     * @param id
     * @return
     */
    public CardDB getCard(int id) {
        return cardMap.get(id);
    }

    public void removeSleepCard(int cardId) {
        CardDB cardDB = getCard(cardId);
        if (cardDB == null)
            return;

        if (cardDB.battle)
            return;

        sleepCardList.remove(cardDB);
        cardMap.remove(cardId);
        player.addChangeGoods(SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_CARDS, cardId, -1, 0);
    }

    public boolean isBattle(int cardId) {
        return cardMap.get(cardId) == null ? false : cardMap.get(cardId).battle;
    }

    public void addBattleCard(CardDB cardDB) {
        if (cardMap.get(cardDB.id) != null)
            return;

        cardDB.battle = true;
        battleCardList.add(cardDB);
        cardMap.put(cardDB.id, cardDB);
    }

    public void addSleepCard(CardDB cardDB) {
        if (cardMap.get(cardDB.id) != null)
            return;

        cardDB.battle = false;
        sleepCardList.add(cardDB);
        cardMap.put(cardDB.id, cardDB);
    }

    public List<CardDB> getBattleCardList() {
        return battleCardList;
    }

    public List<CardDB> getAllCardList() {
        List<CardDB> tempList = new CopyOnWriteArrayList<>();
        tempList.addAll(battleCardList);
        tempList.addAll(sleepCardList);
        return tempList;
    }

    public List<CardDB> getSleepCardList() {
        return sleepCardList;
    }

    public Map<Integer, CardDB> getCardMap() {
        return cardMap;
    }

    public int getEquipLvCount(int targetLv) {
        EquipDB equipDB = null;
        int count = 0;
        for (CardDB cardDB : cardMap.values()) {
            for (Map.Entry<Integer, EquipDB> e : cardDB.getEquipMap().entrySet()) {
                equipDB = cardDB.getEquipDB(e.getKey());
                if (equipDB.getLv() >= targetLv) {
                    count += 1;
                }

            }
        }
        return count;
    }

    /**
     * 获取超过X合成次数的装备件数
     *
     * @param syncTimes
     * @return
     */
    public int getEquipSyncCount(int syncTimes) {
        int count = 0;
        for (CardDB cardDB : cardMap.values()) {
            for (EquipDB equipDB : cardDB.getEquipMap().values()) {
                if (equipDB.upCount >= syncTimes) {
                    count += 1;
                }

            }
        }
        return count;
    }

    /**
     * 获取指定等级饰品数量
     *
     * @param targetLv
     * @return
     */
    public int getAccessoryCountByTargetLv(int targetLv) {
        int count = 0;
        for (CardDB cardDB : cardMap.values()) {
            for (AccessoryDB accessoryDB : cardDB.getAccessoryMap().values()) {
                if (accessoryDB.getLv() >= targetLv) {
                    count += 1;
                }
            }
        }
        return count;
    }

    /**
     * 获取指定进阶等级饰品数量
     *
     * @param targetLv
     * @return
     */
    public int getAccessoryUpLvCountByTargetLv(int targetLv) {
        int count = 0;
        for (CardDB cardDB : cardMap.values()) {
            for (AccessoryDB accessoryDB : cardDB.getAccessoryMap().values()) {
                if (accessoryDB.upLv >= targetLv) {
                    count += 1;
                }
            }
        }
        return count;
    }

    /**
     * 获取指定品质和星级的卡牌
     *
     * @param quality
     * @param star
     * @return
     */
    public int getQualityAndStarCount(int quality, int star) {
        int count = 0;
        for (CardDB cardDB : cardMap.values()) {
            if (cardDB.getQuality() >= quality && cardDB.star >= star) {
                count++;
            }
        }
        return count;
    }

    public boolean notingError(PlayerController playerController, CardDB cardDB) {
        if (cardDB == null) {
            // 卡牌不存在
            playerController.sendWarn(WordFactory.CARD_NOTHING_ERROR);
            return true;
        }
        return false;
    }

    /*****************************************
     * 军团连锁
     ***************************************************/
    /**
     * 计算连锁
     *
     * @param chinaType
     */
    public boolean calculateLegionChinaResult(E_LegionChinaType chinaType, PlayerController... controller) {
        if (!CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_LEGION_CHAIN, player)) {
            if (controller.length > 0) {
                controller[0].updateFC();
            }
            return false;
        }
        //为true表示有新的连锁加入
        boolean result = false;
        switch (chinaType) {
            case ALL:
                result = calculateAll();
                break;
            case EQUIP_INTENSIFY:
                result = calculateEquipIntensify();
                break;
            case EQUIP_MERGE:
                result = calculateEquipMerge();
                break;
            case HERO_LEVEL:
                result = calculateHeroLevel();
                break;
            case HERO_QUALITY:
                result = calculateHeroQuality();
                break;
            case HERO_STAR:
                result = calculateHeroStar();
                break;
            case ACCESSORY_INTENSIFY:
                result = calculateAccessoryLevel();
                break;
            case ACCESSORY_QUALITY:
                result = calculateAccessoryQuality();
                break;
            case CARD_NUM:
                result = calculateCardNum();
                break;
            default:
                break;
        }

        // LogUtils.debug("解锁连锁：" + legionChinaMap.toString());

        if (controller != null && controller.length > 0) {
            controller[0].updateFC();
        } else {
            player.updateFC(true);
        }

        return result;
    }

    /**
     * 计算上阵数量连锁
     */
    private boolean calculateCardNum() {
        boolean result = false;
        LegionChainConfig legionChainConfig = DataFactory.getInstance().getGameObject(DataFactory.LEGION_CHAIN_KEY,
                E_LegionChinaType.CARD_NUM.getCode());
        int battleNum = getBattleCardList().size() + getSleepCardList().size();
        for (int i = 0; i < legionChainConfig.param.length; i++) {
            if (battleNum >= legionChainConfig.param[i]) {
                legionChinaMap.put(E_LegionChinaType.CARD_NUM.getCode(), i);
                player.getChangeGoods().getLegionChainCacheMap().put(E_LegionChinaType.CARD_NUM.getCode(), i);
                result = true;
            } else {
                break;
            }
        }
        return result;
    }

    /**
     * 计算饰品品质连锁
     */
    private boolean calculateAccessoryQuality() {
        boolean result = false;
        LegionChainConfig legionChainConfig = DataFactory.getInstance().getGameObject(DataFactory.LEGION_CHAIN_KEY,
                E_LegionChinaType.ACCESSORY_QUALITY.getCode());
        List<CardDB> battleCardList = getBattleCardList();
        int min = Integer.MAX_VALUE;
        for (CardDB cardDB : battleCardList) {
            for (AccessoryDB accessoryDB : cardDB.getAccessoryMap().values()) {
                if (accessoryDB.upLv < min)
                    min = accessoryDB.upLv;
            }
        }

        for (int i = 0; i < legionChainConfig.param.length; i++) {
            if (min >= legionChainConfig.param[i]) {
                legionChinaMap.put(E_LegionChinaType.ACCESSORY_QUALITY.getCode(), i);
                player.getChangeGoods().getLegionChainCacheMap().put(E_LegionChinaType.ACCESSORY_QUALITY.getCode(), i);
                result = true;
            } else {
                break;
            }
        }
        return result;
    }

    /**
     * 计算饰品等级连锁
     */
    private boolean calculateAccessoryLevel() {
        boolean result = false;
        LegionChainConfig legionChainConfig = DataFactory.getInstance().getGameObject(DataFactory.LEGION_CHAIN_KEY,
                E_LegionChinaType.ACCESSORY_INTENSIFY.getCode());
        List<CardDB> battleCardList = getBattleCardList();
        int min = Integer.MAX_VALUE;
        for (CardDB cardDB : battleCardList) {
            for (AccessoryDB accessoryDB : cardDB.getAccessoryMap().values()) {
                if (accessoryDB.getLv() < min)
                    min = accessoryDB.getLv();
            }
        }

        for (int i = 0; i < legionChainConfig.param.length; i++) {
            if (min >= legionChainConfig.param[i]) {
                legionChinaMap.put(E_LegionChinaType.ACCESSORY_INTENSIFY.getCode(), i);
                player.getChangeGoods().getLegionChainCacheMap().put(E_LegionChinaType.ACCESSORY_INTENSIFY.getCode(), i);
                result = true;
            } else {
                break;
            }
        }
        return result;
    }

    /**
     * 计算英雄星级连锁
     */
    private boolean calculateHeroStar() {
        boolean result = false;
        LegionChainConfig legionChainConfig = DataFactory.getInstance().getGameObject(DataFactory.LEGION_CHAIN_KEY,
                E_LegionChinaType.HERO_STAR.getCode());
        List<CardDB> battleCardList = getBattleCardList();
        int min = Integer.MAX_VALUE;
        for (CardDB cardDB : battleCardList) {
            int star = cardDB.star;
            if (star < min) {
                min = star;
            }
        }

        for (int i = 0; i < legionChainConfig.param.length; i++) {
            if (min >= legionChainConfig.param[i]) {
                legionChinaMap.put(E_LegionChinaType.HERO_STAR.getCode(), i);
                player.getChangeGoods().getLegionChainCacheMap().put(E_LegionChinaType.HERO_STAR.getCode(), i);
                result = true;
            } else {
                break;
            }
        }
        return result;
    }

    /**
     * 计算英雄品质连锁
     */
    private boolean calculateHeroQuality() {
        boolean result = false;
        LegionChainConfig legionChainConfig = DataFactory.getInstance().getGameObject(DataFactory.LEGION_CHAIN_KEY,
                E_LegionChinaType.HERO_QUALITY.getCode());
        List<CardDB> battleCardList = getBattleCardList();
        Map<Integer, Integer> qualityCountMap = new HashMap<>();
        for (CardDB cardDB : battleCardList) {
            Integer quality = qualityCountMap.get(cardDB.getConfig().quality);
            quality = quality == null ? 0 : quality;
            qualityCountMap.put(cardDB.getConfig().quality, quality + 1);
        }

        for (int i = legionChainConfig.param.length - 1; i >= 0; i--) {
            int param = legionChainConfig.param[i];
            int quality = param / 100;
            // Integer count = qualityCountMap.get(quality);
            // count = count == null ? 0 : count;
            int count = getUpQualityCount(qualityCountMap, quality);
            if (count >= param % 100) {
                legionChinaMap.put(E_LegionChinaType.HERO_QUALITY.getCode(), i);
                player.getChangeGoods().getLegionChainCacheMap().put(E_LegionChinaType.HERO_QUALITY.getCode(), i);
                result = true;
                break;
            }
        }
        return result;
    }

    public int getUpQualityCount(Map<Integer, Integer> qualityCountMap, int quality) {
        int count = 0;
        for (Map.Entry<Integer, Integer> entry : qualityCountMap.entrySet()) {
            if (entry.getKey() >= quality)
                count += entry.getValue();
        }
        return count;
    }

    /**
     * 计算英雄等级连锁
     */
    private boolean calculateHeroLevel() {
        boolean result = false;
        LegionChainConfig legionChainConfig = DataFactory.getInstance().getGameObject(DataFactory.LEGION_CHAIN_KEY,
                E_LegionChinaType.HERO_LEVEL.getCode());
        List<CardDB> battleCardList = getBattleCardList();
        int min = Integer.MAX_VALUE;
        for (CardDB cardDB : battleCardList) {
            int star = cardDB.getLv();
            if (star < min) {
                min = star;
            }
        }

        for (int i = 0; i < legionChainConfig.param.length; i++) {
            if (min >= legionChainConfig.param[i]) {
                legionChinaMap.put(E_LegionChinaType.HERO_LEVEL.getCode(), i);
                player.getChangeGoods().getLegionChainCacheMap().put(E_LegionChinaType.HERO_LEVEL.getCode(), i);
                result = true;
            } else {
                break;
            }
        }
        return result;
    }

    /**
     * 计算装备合成连锁
     */
    private boolean calculateEquipMerge() {
        boolean result = false;
        LegionChainConfig legionChainConfig = DataFactory.getInstance().getGameObject(DataFactory.LEGION_CHAIN_KEY,
                E_LegionChinaType.EQUIP_MERGE.getCode());
        List<CardDB> battleCardList = getBattleCardList();
        int min = Integer.MAX_VALUE;
        for (CardDB cardDB : battleCardList) {
            for (EquipDB equipDB : cardDB.getEquipMap().values()) {
                if (equipDB.upCount < min)
                    min = equipDB.upCount;
            }
        }

        for (int i = 0; i < legionChainConfig.param.length; i++) {
            if (min >= legionChainConfig.param[i]) {
                legionChinaMap.put(E_LegionChinaType.EQUIP_MERGE.getCode(), i);
                player.getChangeGoods().getLegionChainCacheMap().put(E_LegionChinaType.EQUIP_MERGE.getCode(), i);
                result = true;
            } else {
                break;
            }
        }
        return result;
    }

    /**
     * 计算装备强化连锁
     */
    private boolean calculateEquipIntensify() {
        boolean result = false;
        LegionChainConfig legionChainConfig = DataFactory.getInstance().getGameObject(DataFactory.LEGION_CHAIN_KEY,
                E_LegionChinaType.EQUIP_INTENSIFY.getCode());
        List<CardDB> battleCardList = getBattleCardList();
        int min = Integer.MAX_VALUE;
        for (CardDB cardDB : battleCardList) {
            for (EquipDB equipDB : cardDB.getEquipMap().values()) {
                if (equipDB.getLv() < min)
                    min = equipDB.getLv();
            }
        }

        for (int i = 0; i < legionChainConfig.param.length; i++) {
            if (min >= legionChainConfig.param[i]) {
                legionChinaMap.put(E_LegionChinaType.EQUIP_INTENSIFY.getCode(), i);
                player.getChangeGoods().getLegionChainCacheMap().put(E_LegionChinaType.EQUIP_INTENSIFY.getCode(), i);
                result = true;
            } else {
                break;
            }
        }
        return result;
    }

    /**
     * 计算所有条件连锁
     */
    public boolean calculateAll() {
        if (battleCardList.size() != 0)
        {
            legionChinaMap.clear();
            boolean r1 = calculateEquipIntensify();
            boolean r2 = calculateEquipMerge();
            boolean r3 = calculateHeroLevel();
            boolean r4 = calculateHeroQuality();
            boolean r5 = calculateHeroStar();
            boolean r6 = calculateAccessoryLevel();
            boolean r7 = calculateAccessoryQuality();
            boolean r8 = calculateCardNum();

            return r1 || r2 || r3 || r4 || r5 || r6 || r7 || r8;
        }
        return false;
    }

    /**
     * 获取军团连锁结果
     *
     * @return
     */
    public Map<Integer, Integer> getLegionChinaMap() {
        return legionChinaMap;
    }




}
